<?php
//添加修复记录
include_once __DIR__ . '/../BaseShell.php';
while (true) {
    $ticket = Lib_Redis_List::LPop("YunKeFu_CALL_TICKET");
    $log =  "ticket = " . $ticket;
    if (empty($ticket)) {//话单
        sleep(5);
        continue;
    }
    $ticket = json_decode($ticket, true);
    if($ticket['down_time'] > time()){
        sleep($ticket['down_time'] - time());
    }
    $mainUniqueId = $ticket['mainUniqueId'];
    $log .= ' callId = ' . $mainUniqueId ;
    $push_data = $ticket['push_data'];
    $file_name = '';
    $case_data = [];
    $talk_type = 2;
    $call_type = $ticket['hangup_type'] == 'callOut' ? 1 : 2;
    //查询是否是投诉建议
    if(Lib_Redis_String::get($mainUniqueId."_suggestion")){
        $call_type = 3;
    }
    $callPhone = $call_type == 1 ? $push_data['CalledNo'] : $push_data['CallNo'];
    $callinNumber = $call_type == 1 ? $push_data['CallNo'] : $push_data['CalledNo'];
    $workerId =  $push_data['Agent'];
    if (in_array($push_data['State'], ['dealing','voicemail'])) {
        $talk_type = 1;
        $talk_time = strtotime($push_data['End'])-strtotime($push_data['Begin']);
        if(!empty($push_data['FileServer']) && !empty($push_data['RecordFile'])){
            //下载录音等待1分钟
            if(($push_data['down_time'] - time()) > 0){
                sleep($push_data['down_time'] - time());
            }
            $file_name = downloadFile($push_data['FileServer'].'/'.$push_data['RecordFile'],$mainUniqueId);
        }else{
            $file_name = '';
        }
    } else {
        $talk_time = 0;
    }
    if($call_type == 1){
        $case_id = Lib_Redis_String::get("CALL-CASEID" . $push_data['ActionID']);
        $mobileType = Lib_Redis_String::get("CALL-MOBILETYPE" . $push_data['ActionID']);
    }else{
        $case_id = Lib_Redis_String::get("CALL-CASEID" . $mainUniqueId);
    }
    if (empty($case_id)){
        $caseLitigant = Module_Mediate_CaseLitigant::getInstance()->getOne(['caseId'],["telephone={$callPhone} order by id DESC" ]);
        $case_id = $caseLitigant['caseId'];
    }
    if (!empty($case_id)) {
        $case_data = Module_Mediate_Case::getInstance()->getItemById($case_id, true);
    }
    if ($workerId) {
        $worker_data = Module_Mediate_Workernumber::getInstance()->getOne([],["workerId={$workerId}","isDel=1"]);

    }
    //直接 用软化机拨打电话, 没有案件信息
    if(empty($case_data)){
        Func_Log::write('call_record', "empty cases", $log);
        //拿到这个手机号全部的案件,匹配组织
        $litigant= Module_Mediate_CaseLitigant::getInstance()->getAllBySearch(['caseId'],['where'=>["telephone = '{$callPhone}'"]]);
        if (!empty($litigant) && !empty($worker_data['mediationOrganId'])) {
            $litigant = array_column($litigant, 'caseId');
            $caseIdStr = implode(",", $litigant);
            $case_data = Module_Mediate_Case::getInstance()->getone([], ["id in ({$caseIdStr})", "mediationOrganId={$worker_data['mediationOrganId']}"]);
        }
        if (!empty($worker_data)) {
            $case_data['mediationOrganId'] = $worker_data['mediationOrganId'];
        }
    }
    if(!empty($case_data['id'])){
        $log .=  ' caseId = ' . $case_data['id'];
    }
    $call_recode = [
        'callName' => !empty($case_data['litigantName']) ? $case_data['litigantName'] : '',
        'callinNumber' => $callinNumber,
        'callPhone' => $callPhone,
        'callType' => $call_type,
        'callTime' => strtotime($push_data['Ring']),
        'callEndTime' => strtotime($push_data['End']),
        'talkTime' => $talk_time,
        'talkType' => $talk_type,
        'callId' => $ticket['mainUniqueId'],
        'fileName' => $file_name,
        'caseId' => !empty($case_data['id']) ? $case_data['id'] : '',
        'assetsId' =>  !empty($case_data['assetsId']) ? $case_data['assetsId'] : 0,
        'importRecordId' =>  !empty($case_data['importRecordId']) ? $case_data['importRecordId'] : 0,
        'mobileType' =>  !empty($mobileType) ? $mobileType : 1,
        'workerId' => $workerId,
        'mediatorId' => !empty($worker_data['mediatorId']) ? $worker_data['mediatorId'] : 0,
        'mediatorName' => !empty($worker_data['mediator']) ? $worker_data['mediator'] : '',
        'mediationOrganId' => !empty($case_data['mediationOrganId']) ? $case_data['mediationOrganId'] : 0,
        'contractNo' => !empty($case_data['contractNo']) ? $case_data['contractNo'] : '',
        'addTime' => time(),
    ];
    $record_res = Module_Mediate_CallRecord::getInstance()->singleInsert($call_recode);
    if (!$record_res) {
        Func_Log::write('call_record', "add callout record errror", $log . "call_recode = " . json_encode($call_recode) );
    }
    Func_Log::write('call_record', "add callout success",  $log . "call_recode = " . json_encode($call_recode));
    //呼入添加号码
    if(in_array($call_type,[2,3]) && !empty($case_data['id'])) {
        //判断是否存在
        $history = Module_Mediate_CaseLitigant::getInstance()->getOne(['*'],["caseId = {$case_data['id']}","telephone = {$callPhone} and isDel = 0"]);
        if (empty($history)) {
            $litigant = Module_Mediate_CaseLitigant::getInstance()->getOne(['*'],["caseId = {$case_data['id']} order by id DESC"]);
            if (!empty($litigant)) {
                $res = Module_Mediate_CaseLitigant::getInstance()->singleInsert(
                    [
                        'caseId' => $case_data['id'],
                        'litigantName' => $litigant['litigantName'],
                        'cardId' => $litigant['cardId'],
                        'telephone' => $callPhone,
                        'mobileSource' => 2,
                    ]
                );
            }
        }

    }
    if($call_type == 3){
        $call_recode = [
            'callPhone' => $callPhone,
            'callTime' => strtotime($push_data['Ring']),
            'callEndTime' => strtotime($push_data['End']),
            'talkTime' => $talk_time,
            'talkType' => $talk_type,
            'fileName' => $file_name,
            'addTime' => time(),
            'callId' => $mainUniqueId
        ];
        //投诉建议添加记录
        $record_res = Module_Mediate_Suggestion::getInstance()->insert($call_recode);
        if (!$record_res) {
            Func_Log::write('call_record', "add call suggestion record errror", "call_recode = " . $call_recode . ' mainUniqueId = ' . $mainUniqueId);
        }
    }
    //增加 判断 必须有$caseId  在生成记录
    if (!empty($case_data['id']) && $call_type != 3) {
        $case_mediate = [
            'caseId' => $case_data['id'],
            'mediatorId' => !empty($worker_data['mediatorId']) ? $worker_data['mediatorId'] : 0,
            'mediatorName' => !empty($worker_data['mediator']) ? $worker_data['mediator'] : '',
            'mobileType' =>  !empty($mobileType) ? $mobileType : 1,
            'type' => $call_type,
            'mobile' => $callPhone,
            'fileName' => $file_name,
            'callId' => $mainUniqueId,
            'addTime' => time()
        ];
        $todayContactStutus = $talk_type == 1 ? 3 : 2;
        if(in_array($case_data['todayContactStutus'],[1,2]) && $todayContactStutus != $case_data['todayContactStutus']){
            $save_case = [
                'todayContactStutus'=>$todayContactStutus,
                'lastCallTime'=>time(),
                'updateTime'=>time()
            ];
        }
        $res = Module_Mediate_CaseMediateLog::getInstance()->insert($case_mediate,$save_case);
        if (!$res) {
            Func_Log::write('call_record', "add case mediate errror", "case_mediate = " . json_encode($case_mediate));
        }
        if(in_array($case_data['repayStatus'],['wait_repay','break_repay', 'keep_repay','finish_repay'])){
            Module_Mediate_ReturnedMoneyPlan::getInstance()->singleUpdate(['caseId'=> $case_data['id'],'todayContactStutus'=>$todayContactStutus],'caseId');
        }
    }

    //统计
    $historylong = 0;//避免循环出错
    $history = Lib_Redis_Hash::hGetAll($workerId);
    if($call_type == 1){
        if($talk_type == 1){//呼出
            Lib_Redis_Hash::hIncrby($workerId,'callout_on',1);
            Lib_Redis_Hash::hIncrby($workerId,'callout_time',$call_recode['talkTime']);
        }else{
            Lib_Redis_Hash::hIncrby($workerId,'callout_not',1);
        }
        $historylong = Lib_Redis_Hash::hGet($workerId,'callout_max_long');
        if(empty($historylong) || $historylong < $call_recode['talkTime'] ){
            Lib_Redis_Hash::hSet($workerId,'callout_max_long',$call_recode['talkTime']);
        }

    }else{
        if($talk_type == 1){//呼入
            Lib_Redis_Hash::hIncrby($workerId,'callin_on',1);
            Lib_Redis_Hash::hIncrby($workerId,'callin_time',$call_recode['talkTime']);
        }else{
            Lib_Redis_Hash::hIncrby($workerId,'callin_not',1);
        }
        $historylong = Lib_Redis_Hash::hGet($workerId,'callin_max_long');
        if(empty($historylong) || $historylong < $call_recode['talkTime'] ){
            Lib_Redis_Hash::hSet($workerId,'callin_max_long',$call_recode['talkTime']);
        }
    }
    if($history){
        Lib_Redis_Hash::expireAt($workerId, strtotime(date('Y-m-d 23:59:59')));
    }
}
function downloadFile($downUrl,$CallSheetID){
    Func_Log::write('call_record', "downloadFile {$CallSheetID}",$downUrl);
    //初始化文件
    $save_date = date('Y-m-d').'/';
    $savePath = LIBRARY_DIR."/../evidencefiles/callrecord/".$save_date;
    if(!file_exists($savePath)){
        if(!@mkdir($savePath,0777,true)){
            Func_Log::write('call_record', "Can not make dir",$savePath);
            return '';
        }
    }
    //录音已经下载
    if(file_exists($savePath.$CallSheetID.'.mp3')){
        return $save_date.$CallSheetID.'.mp3';
    }
    sleep(1);
    if($downUrl){
        $header_array = get_headers($downUrl, true);
        $size = $header_array['Content-Length'];
        $type = $header_array['Content-Type'];
        if (!$size || strstr($type,'audio') === false || $size < 500){
            $num = Lib_Redis_String::get("DOWNLOADFILE" . $CallSheetID);
            $num = $num ? $num : 1;
            if($num > 5){
                return '';
            }
            Lib_Redis_String::setex("DOWNLOADFILE" . $CallSheetID,1800,$num+1);
            sleep(5);
            Func_Log::write('call_record', "downUrl empty data","downUrl = ".$downUrl );
            return downloadFile($downUrl,$CallSheetID);
        }
    }else{
        Func_Log::write('call_record', "downloadFile empty downUrl","CallSheetID = ".$CallSheetID );
        return '';
    }
    //下载文件
    $url = $downUrl;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $fp = fopen($savePath.$CallSheetID.'.mp3', 'w');
    $result = fwrite($fp, $rawdata);
    fclose($fp);
    if($result && file_exists($savePath.$CallSheetID.'.mp3')){
        return $save_date.$CallSheetID.'.mp3';
    }
    if (strlen($rawdata) < 100){
        Func_Log::write('call_record', "downloadFile fail","CallSheetID = ".$CallSheetID ."res = ",var_export($result,1).$rawdata);
    }
    Func_Log::write('call_record', "downloadFile fail","CallSheetID = ".$CallSheetID ."res = ",var_export($result,1));
    $num = Lib_Redis_String::get("DOWNLOADFILE" . $CallSheetID);
    $num = $num ? $num : 1;
    if($num > 5){
        return '';
    }
    Lib_Redis_String::setex("DOWNLOADFILE" . $CallSheetID,1800,$num+1);
    return downloadFile($downUrl,$CallSheetID);
}
